/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.theorcs.chronicles.tapestry.components.persona;

import org.apache.tapestry5.Asset;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.alerts.AlertManager;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.upload.services.UploadedFile;
import org.libermundi.theorcs.chronicles.dto.ChronicleSettings;
import org.libermundi.theorcs.chronicles.model.Persona;
import org.libermundi.theorcs.chronicles.services.PersonaManager;
import org.libermundi.theorcs.chronicles.tapestry.pages.perso.Description;
import org.libermundi.theorcs.core.tapestry.services.assets.FileManager;
import org.libermundi.theorcs.core.tapestry.services.assets.FileType;
import org.libermundi.theorcs.core.tapestry.services.assets.FileValidator;
import org.libermundi.theorcs.core.tapestry.services.assets.OfsFilesUtils;
import org.libermundi.theorcs.core.tapestry.services.assets.OrcsFileSystem;

import com.google.common.base.Strings;

/**
 * @author Martin Papy
 *
 */
public class EditDescription {
	@SessionState
	private ChronicleSettings _chronicleSettings;
	
	@Inject
	private PersonaManager _personaManager;
	
	@Inject
	private AlertManager _alertManager;
	
	@Inject
	private Messages _messages;
	
	@Inject
	private FileValidator _validator;
	
    @Inject
    private ComponentResources _resources;
    
    @Inject
    private Request _request;
    
    @Inject
    @Symbol(SymbolConstants.ASSET_PATH_PREFIX)
    private String _t5AssetPrefix;
    
    @Inject
    @OrcsFileSystem
    private FileManager _fileManager;
	
	@Component
	private Form _editDescriptionForm;
	
	/*------------- Fields for editDescriptionForm -------------*/
	@Property(write=false)
	private String _persoName; 

	@Property
	private String _persoDescription;
	
	@Property
	private UploadedFile _persoPicture;
	
	@Property
	private boolean _deletePicture;
	
	/*------------- Render Phases -------------*/
	@SetupRender
	public void setupRender(){
		Persona currentPerso = _chronicleSettings.getPersona();
			_persoName = currentPerso.getName();
			_persoDescription = currentPerso.getDescription();
	}
	
	/*------------- Form Events -------------*/
	@OnEvent(value="validate",component="editDescriptionForm")
	public void validate(){
		if((_persoPicture != null) && !_validator.isAllowed(_persoPicture.getFileName(), FileType.IMAGE)){
			_editDescriptionForm.recordError(_messages.get("chronicles.error.filenotallowed"));
		}
	}	
	
	@OnEvent(value="success",component="editDescriptionForm")
	public Class<?> success(){
		Persona currentPerso = _chronicleSettings.getPersona();
		currentPerso.setDescription(_persoDescription);
		
		if(_persoPicture != null){
			_deletePicture = Boolean.TRUE;
		}
		
		if(_deletePicture){
			if(!Strings.isNullOrEmpty(currentPerso.getPicture())) {
				_fileManager.delete(OfsFilesUtils.stripPrefix(currentPerso.getPicture()));
			}
			currentPerso.setPicture(null);
		}
		
		if(_persoPicture != null){
			Asset savedPicture = _fileManager.save(_persoPicture,FileType.IMAGE);
			currentPerso.setPicture(OfsFilesUtils.getPrefixedPathFromUrl(savedPicture.toClientURL(), _request, _t5AssetPrefix));
		}
		
		_personaManager.save(currentPerso);

		// At this point we should send an Activation Email to the User
		_alertManager.success(_messages.get("chronicles.persona.management.description.edit.success"));

		return Description.class;
	}
}
